import { HttpClient } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzImageModule } from 'ng-zorro-antd/image';

import { Api } from '../api';

@Component({
  selector: 'app-preview-image',
  template: `<img #image nz-image width="100px" height="50px" [nzSrc]="imageSrc" [nzFallback]="fallback" [nzPlaceholder]="fallback" />`,
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: true,
  imports: [NzImageModule]
})
export class ImagePreviewComponent implements OnInit {
  @Input() width: number = 100;
  @Input() height: number = 50;
  @Input() record: any = {};

  imagePreviewUrl: string = `${Api.BasePreviewApi}/`;

  fallback =
    '';

  imageSrc: string = '';
  constructor(private httpClient: HttpClient) {}

  @ViewChild('image') image!: any;

  ngOnInit(): void {
    if (this.record && this.record.id) {
      const url = this.imagePreviewUrl + this.record.id;
      this.httpClient.get(url, { responseType: 'blob' }).subscribe(blob => {
        this.imageSrc = URL.createObjectURL(blob);
      });
    }
  }
}
